package com.zz.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Copyright Zz
 * FileName: DruidConfig
 * Author:   Zz
 * Date:     2023/6/122:59
 * Description:Druid数据库连接池配置
 * hISTORY:
 * <author>  <time>     <version>    <desc>
 * 作者姓名   修改时间       版本号       描述
 */
@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    // 后台监控
    // springboot 内置了servlet 容器，没有web.xml,替代方法：ServletRegistrationBean
    @Bean
    public ServletRegistrationBean StatViewServlet() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        // 后台登录，账号密码配置
        Map<String, String> initParameters = new HashMap<>();

        // 增加配置

        // 登录的key是固定的（loginUsername和loginPassword）
        initParameters.put("loginUsername", "admin");
        initParameters.put("loginPassword", "123456");

        // 允许谁能访问
        initParameters.put("allow", "");// 表示所有主机都可以访问

      /*  // 禁止谁能访问
         initParameters.put("xsw","192.168.5.6");*/

        bean.setInitParameters(initParameters);// 设置初始化参数

        return bean;
    }

    // fliter
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();

        bean.setFilter(new WebStatFilter());


        // 可以过滤哪些请求
        Map<String, String> initParameters = new HashMap<>();

        // 这些东西不进行统计
        initParameters.put("exclusions", "*.js,*.css,/druid/*");

        bean.setInitParameters(initParameters);

        return bean;
    }
}
